import { BASE_URL, CONTEXT } from '@/app.config';
import { showToast } from '@/utils/util'
import { customNavigate, customRedirect } from '@/utils/route'

function request({
    url,
    method,
    data,
    loading,
    header = {}
}) {
    return new Promise((resolve, reject) => {
        const APP_URL = BASE_URL + CONTEXT;

        if (!url) throw new Error('request url is not defined');
        if (!method) throw new Error('request method is not defined');

        method = method.toUpperCase();
        header['token'] = (url === '/elderly/toggle_elderly') ?
            wx.getStorageSync('userInfo')['token'] :
            (url === '/elderly/registered') ? header.token : wx.getStorageSync('elderlyInfo')['token'];

        const handleError = (message, redirectToLogin = false) => {
            showToast(message, redirectToLogin ? () => {
                wx.clearStorage();
                customRedirect({
                    url: '/User/pages/Login/index'
                });
            } : undefined);
        };

        const statusCodeHandlers = {
            401: () => handleError('登录状态失效，请重新登录', true),
            404: () => handleError('接口地址异常，请联系管理员'),
            500: () => handleError('服务连接异常，请联系管理员'),
            default: (code) => {
                throw new Error(`请求失败: ${code}`);
            }
        };
        wx.request({
            url: `${APP_URL}${url}`,
            method,
            data,
            header,
            success: (res) => {
                const {
                    statusCode,
                    data: resData
                } = res;

                if (statusCode === 200) {
                    if (resData.return_code === 'FAIL') {
                        if (resData.return_msg.includes('token异常')) {
                            handleError('登录过期，请重新登录', true);
                        } else {
                            showToast(resData.return_msg);
                            reject(resData);
                        }
                    } else {
                        resolve(resData);
                    }
                } else {
                    (statusCodeHandlers[statusCode] || statusCodeHandlers.default)(statusCode);
                }
            },
            fail: (err) => {
                handleError('网络请求失败');
                throw err;
            }
        });
    });
}


module.exports = {
    request
};